<template>
  <view class="page-wrap">
<!--    <u-navbar right-icon="scan" placeholder auto-back bg-color="#00000000" title="亲情账户绑定" @right-click="toScan" @left-click="jumpRelated" />-->
<!--    <view style="position: absolute;width: 20px;height: 20px;right: 40px;z-index: 999" @click="news">-->
<!--      <image src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/book/xiaoXi.png"-->
<!--             style="width: 100%;height: 100%;"></image>-->
<!--      <u-badge type="warning" :isDot="!!unreadCount" style="position: absolute;right: 0;top: -2px"></u-badge>-->
<!--    </view>-->
    <view class="px-4">
      <view v-if="currentBinding" class="binding-phone flex-c-c">
        已绑定孩子账号：{{ currentBinding }}
      </view>
      <view class="flex-c-c bingding-container relative w-full">
        <view class="qr-area">
          <view class="qr-bg">
            <image class="qr-star qr-star1" src="https://img.icons8.com/color/48/000000/star--v1.png" mode="widthFix"/>
            <image class="qr-star qr-star2" src="https://img.icons8.com/color/48/000000/star--v1.png" mode="widthFix"/>
            <image class="qr-decor" src="https://img.icons8.com/ios-filled/50/8B4513/open-book--v2.png" mode="widthFix" />
            <view class="qr-card">
              <image class="binding-my-qr" :src="myQr" mode="scaleToFill" @click="getMyQRCodeData" />
            </view>
            <view class="qr-wave"></view>
          </view>
          <view class="qr-tip">扫码绑定孩子</view>
          <view class="qr-tip" style="font-size: 46rpx;">让孩子开启学习成长之旅</view>
        </view>
      </view>
      <view class="binding-info flex">
<!--        <view class="fontSize-32 text-center">-->
<!--          扫一扫二维码，督促孩子学习-->
<!--        </view>-->
        <view v-if="!currentBinding" class="flex-column flex gap-20 py-10 text-center">
          <view v-if="!bingdingList.length">
            当前未有绑定的孩子账号
          </view>
          <u-button
            type="primary" color="#8B4513" shape="circle" style="width: 90%;margin: auto" size="large" text="去绑定孩子"
            @click="toScan"
          />
        </view>
        <view v-if="bingdingList.length" class="flex-column flex gap-20 py-10">
          <view style="position: relative;width: 100%">
            当前绑定孩子账号
            <text style="color: #989898;font-size: 20rpx">
              点击账号即可切换
            </text>
            <text v-if="token2" style="position: absolute;right: 10px;color: #989898;font-size: 20rpx" @click="back">切换回自己账号</text>
          </view>
          <view
            v-for="(item, index) in bingdingList" :key="item.userId"
            class="bg-neutralBgcColor rounded-10 py-4 text-left"
          >
            <view class="txtDescColor flex-b-c mx-10" style="color: #666666">
              <view @click="toggle(index)">
                绑定账户{{ index + 1 }}： {{ item.nickName }}
              </view>
              <image
                class="bing-img" src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/bangDing.png" mode="scaleToFill"
                @click.stop="unBindRelation(index)"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { bindMyQRCode, getMyQRCode, getMyRelationApi, switchBindUser, unBindRelationApi, unreadMessage } from '@/api/binding.js';

export default {
  data() {
    return {
      token2: '',
      currentBinding: '',
      myQr: '',
      bingdingList: [],
      statusBarHeight: 0,
      unreadCount: 0,
      unreadTimer: null
    };
  },
  methods: {
    async unBindRelation(index) {
      try {
        let childId = this.bingdingList[index].id
        let t1 = this.$store.state.app.token1
        let t2 = this.$store.state.app.token2
        if (t1 !== '' && t1) {
          this.$store.commit('LOGIN', {token: t1})
        }
        await unBindRelationApi({ userId: childId }).then(res=>{
          if (res && res.code) {
            // 如果没有绑定账户，自动切回自己并清空 token1、token2
            if (this.bingdingList.length-1 <= 0) {
              this.$store.commit('LOGIN', {token: t1});
              this.$store.commit('SET_TOKEN1', '');
              this.$store.commit('SET_TOKEN2', '');
              this.token2 = '';
              uni.showToast({
                title: "解除成功并切换回自己账户",
                icon: 'none'
              });
            } else {
              uni.showToast({
                title: "解除成功",
                icon: 'none'
              });
              if (t1 !== '' && t1) {
                this.$store.commit('LOGIN', {token: t2})
              }
            }
            this.initData();
          } else {
          }
        })
      } catch (error) {
        console.log(error);
      }
    },
    back() {
      let t1 = this.$store.state.app.token1
      if (t1) {
        this.$store.commit('LOGIN', {token: t1})
        this.$store.commit('SET_TOKEN1', '')
        this.$store.commit('SET_TOKEN2', '')
        this.token2 = this.$store.state.app.token2
        uni.showToast({
          title: "已成功换回自己账户",
          icon: 'none'
        });
      }
    },
    async toggle(index) {
      try {
        let currentToken = this.$store.state.app.token
        let backupToken = this.$store.state.app.token1
        if (backupToken) {
          uni.showToast({
            title: "请先切换回自己账户",
            icon: 'none'
          });
          return;
        }
        let childId = this.bingdingList[index].id
        await switchBindUser(childId).then(res => {
          if (res && res.code) {
            uni.showToast({
              title: "切换成功",
              icon: 'none'
            });
            console.log(res)
            this.$store.commit('SET_TOKEN1', currentToken) // 备份自己token
            this.$store.commit('SET_TOKEN2', res.data.token) // 备份自己token
            this.$store.commit('LOGIN', res.data)    // 切换到孩子token
            console.log(this.$store.state.app.token)
            this.token2 = this.$store.state.app.token2
          }
        })
      } catch (error) {
        console.log(error);
      }
    },
    async getMyQRCodeData() {
      try {
        await getMyQRCode().then(res=>{

          this.myQr = res.data.code;
          if (!res.data) {
          }
        });
      } catch (error) {}
    },
    async getMyRelation() {
      try {
        console.log(this.$store.state.app.token)
        console.log(this.$store.state.app.token1)
        console.log(this.$store.state.app.token2)
        let t1 = this.$store.state.app.token1
        let t2 = this.$store.state.app.token2
        if (t1 !== '' && t1) {
          console.log(111)
          this.$store.commit('LOGIN', {token: t1})
          // this.$store.commit('SET_TOKEN1', t)
          // this.$store.commit('SET_TOKEN2', t2)
        }
        // if (uni.getStorageSync('tokenMe') !== '' && uni.getStorageSync('tokenMe')) {
        //   this.userStore.setUserState('token', uni.getStorageSync('tokenMe'));
        // }
        await getMyRelationApi().then(res=>{
          if (res && res.data) {
            this.bingdingList = res.data;
          }
          if (!res || res.code !== 200) {
          }
        })
        if (t1 !== '' && t1) {
          this.$store.commit('LOGIN', {token: t2})
        }
        // this.userStore.setUserState('token', uni.getStorageSync('token'));
      } catch (error) {
        console.log(error);
      }
    },
    async toScan() {
      try {
        // #ifdef MP || APP
        uni.scanCode({
          success(res) {
            bindMyQRCode(res.result).then(ret=>{
              if (ret.code !== 200) {
                uni.showToast({
                  title: ret.message,
                  icon: 'none'
                });
              } else {
                uni.showToast({
                  title: "已成功发送绑定申请",
                  icon: 'none'
                });
              }
            })
              //   .catch(err => {
              // return uni.showToast({
              //   title: err
            // icon: 'none'
              // });
            // })
          }
        })
        // #endif
      } catch (error) {
        if (error && error.errMsg === "scanCode:fail method 'uni.scanCode' not supported") {
          uni.showToast({
            title: "当前环境暂不支持",
            icon: 'none'
          });
          return;
        }
      }
    },
    async initData() {
      try {
        await this.getMyQRCodeData();
        await this.getMyRelation();
      } catch (error) {
        console.log(error);
      }
    },
    // news() {
    //   uni.navigateTo({
    //     url: '/pages/common/accounts/applicationRecord',
    //   });
    // },
    // async fetchUnreadMessage() {
    //   try {
    //     // if (uni.getStorageSync('tokenMe') !== '' && uni.getStorageSync('tokenMe')) {
    //     //   this.userStore.setUserState('token', uni.getStorageSync('tokenMe'));
    //     // }
    //     let t1 = this.$store.state.app.token1
    //     let t2 = this.$store.state.app.token2
    //     if (t1 !== '' && t1) {
    //       this.$store.commit('LOGIN', t1)
    //       // this.$store.commit('SET_TOKEN1', t)
    //       // this.$store.commit('SET_TOKEN2', t2)
    //     }
    //     const res = await unreadMessage();
    //     if (res.code === 200) {
    //       this.unreadCount = res.data;
    //     }
    //     if (!res || res.code !== 200) {
    //     }
    //     // this.userStore.setUserState('token', uni.getStorageSync('token'));
    //     this.$store.commit('LOGIN', t2)
    //   } catch (error) {
    //     console.log(`获取未读消息报错==>${error}`);
    //   }
    // },
  },
  mounted() {
    // 判断是否为APP平台
    // if (uni.getSystemInfoSync().platform === 'android' || uni.getSystemInfoSync().platform === 'ios') {
    //   setTimeout(() => {
    //     if (typeof plus !== 'undefined') {
    //       const BarHeight = plus.navigator.getStatusbarHeight();
    //       this.statusBarHeight = BarHeight + 12;
    //     }
    //   }, 0);
    // }
    this.token2 = this.$store.state.app.token1
    console.log(this.token2)
    this.initData();
    // this.fetchUnreadMessage();
    // this.unreadTimer = setInterval(this.fetchUnreadMessage, 2000);
  },
  destroyed() {
    if (this.unreadTimer) {
      clearInterval(this.unreadTimer);
      this.unreadTimer = null;
    }
  }
};
</script>

<style lang="scss" scoped>
// 品牌色
$branchColor: #8B4513;
$branchSecondColor: #feeaea;
$branchWeakColor: #fff5f5;
$branchTextColor: #c8102e;
// 功能色
$fncSuccessfulColor: #4cd964;
$fncErrorColor: #ff3b30;
$fncWarnColor: #f7b500;
// 中性色
$neutralDeepBgcColor: #f4f4f4;
$neutralShallowBgcColor: #f9fafa;
$neutralBgcColor: #fbf9f5;
$neutralDeepDividerColor: #dedfde;
$neutralShallowDividerColor: #f7f7f8;
// 文字色
$txtTitleColor: #1a1a1a;
$txtDescColor: #666666;
$txtSupInfColor: #999999;
$txtIconColor: #c8102e;
$txtWhiteColor: #ffffff;

// flex布局
.flex {
  display: flex;
}

.flex-c-c {
  display: flex;
  justify-content: center;
  align-items: center;
}

.flex-b-c {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex-column {
  flex-direction: column;
}

.flex-1 {
  flex: 1;
}

// 文字大小
.fontSize-32 {
  font-size: 32rpx;
}

// 文字颜色
.txtDescColor {
  color: $txtDescColor;
}

// 背景色
.bg-neutralBgcColor {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 18px rgba(139, 69, 19, 0.07);
  margin-bottom: 24rpx;
  padding: 32rpx 24rpx 24rpx 24rpx;
  transition: box-shadow 0.2s;
  position: relative;
}
.bg-neutralBgcColor:hover {
  box-shadow: 0 8px 32px rgba(139, 69, 19, 0.13);
}

// 圆角
.rounded-10 {
  border-radius: 20rpx;
}

// 间距
.gap-20 {
  gap: 20rpx;
}

.py-10 {
  padding: 40rpx;
}

.px-4 {
  padding-left: 12rpx;
  padding-right: 12rpx;
}

.mx-10 {
  margin-left: 40rpx;
  margin-right: 40rpx;
}

// 位置
.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.w-full {
  width: 100%;
}

.text-center {
  text-align: center;
}

.text-left {
  text-align: left;
}

.blurred {
  backdrop-filter: blur(10px);
  /* 背景模糊10px */
  background-color: rgba(255, 255, 255, 0.5);
  /* 半透明背景 */
}

.binding-info {
  flex-direction: column;
  gap: 20rpx;
}

// 美化绑定账户卡片
.bg-neutralBgcColor {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 18px rgba(139, 69, 19, 0.07);
  margin-bottom: 24rpx;
  padding: 32rpx 24rpx 24rpx 24rpx;
  transition: box-shadow 0.2s;
  position: relative;
}
.bg-neutralBgcColor:hover {
  box-shadow: 0 8px 32px rgba(139, 69, 19, 0.13);
}

.txtDescColor {
  color: $txtDescColor;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

// 账户名样式
.txtDescColor > view {
  font-size: 30rpx;
  font-weight: 600;
  color: #8B4513;
  letter-spacing: 1rpx;
  padding: 0 8rpx;
}

// 解绑按钮图片样式
.bing-img {
  width: 44rpx;
  height: 44rpx;
  margin-left: 18rpx;
  cursor: pointer;
  transition: transform 0.15s;
}
.bing-img:active {
  transform: scale(0.92);
}

// 绑定账户标题区域
.binding-info > view:first-child {
  font-size: 28rpx;
  font-weight: 700;
  color: #333;
  margin-bottom: 10rpx;
}

// 切换回自己账户按钮样式
.binding-info text[style*="right: 10px"] {
  color: #8B4513 !important;
  font-weight: 500;
  font-size: 24rpx !important;
  cursor: pointer;
  text-decoration: underline;
}

// 绑定账户为空时的提示
.binding-info > .flex-column > view:first-child {
  color: #bbb;
  font-size: 28rpx;
  margin-bottom: 18rpx;
}

// "去绑定"按钮美化
.u-button[data-v-] {
  background: linear-gradient(90deg, #a86b3c 0%, #8B4513 100%) !important;
  color: #fff !important;
  font-weight: 600;
  font-size: 30rpx;
  border-radius: 40rpx !important;
  box-shadow: 0 2px 8px rgba(139,69,19,0.08);
  margin-top: 12rpx;
}

.binging-radius {
  width: 420rpx;
  height: 420rpx;
  position: absolute;
  border-radius: 50%;
  background-color: rgba(139, 94, 60, 0.1);
  top: calc(50% - 210rpx);
  left: calc(50% - 210rpx);

}

.bing-qrcode {
  background: linear-gradient(135deg, #ffe9c7 0%, #fff6e9 100%);
  background-position: center;
  background-size: 180rpx 180rpx;
  background-repeat: no-repeat;
  overflow: hidden;
  z-index: 2;
  width: 210rpx;
  height: 210rpx;
  border-radius: 32rpx;
  box-sizing: border-box;
  padding: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.qr-decor {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 12rpx;
  opacity: 0.7;
}
.binding-my-qr {
  width: 150rpx;
  max-height: 150rpx;
  border-radius: 12rpx;
  box-shadow: 0 2px 8px rgba(139,69,19,0.08);
}

.bingding-container {
  width: 100%;
  height: 560rpx;
}

.binding-phone {
  margin-top: 80rpx;
  width: 100%;
  flex: 1;
  background-color: #fff;
  border-radius: 60rpx;
  height: 120rpx;
}

.page-wrap {
  padding-bottom: 80rpx;
  background-color: #fbf9f5;
  min-height: 100vh;
  position: relative;
}

.bing-img {
  width: 40rpx;
  height: 40rpx;
}

.qr-area {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 40rpx 0 32rpx 0;
}
.qr-bg {
  width: 320rpx;
  height: 320rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #f9f6f2 0%, #fbeee0 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  position: relative;
  box-shadow: 0 8px 32px rgba(139, 69, 19, 0.07);
  padding-top: 24rpx;
}
.qr-decor {
  width: 48rpx;
  height: 48rpx;
  margin-bottom: 10rpx;
  opacity: 0.8;
  z-index: 2;
}
.qr-card {
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4px 18px rgba(139, 69, 19, 0.10);
  padding: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #ffe0b2;
  z-index: 2;
}
.binding-my-qr {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  box-shadow: 0 2px 8px rgba(139,69,19,0.08);
}
.qr-tip {
  margin-top: 24rpx;
  color: #a86b3c;
  font-size: 40rpx;
  text-align: center;
  letter-spacing: 1rpx;
  font-weight: 600;
}
.qr-star {
  position: absolute;
  width: 28rpx;
  height: 28rpx;
  opacity: 0.7;
  z-index: 1;
}
.qr-star1 {
  left: 18rpx;
  top: 32rpx;
  transform: rotate(-15deg);
}
.qr-star2 {
  right: 18rpx;
  top: 60rpx;
  transform: rotate(10deg);
}
.qr-wave {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 32rpx;
  background: linear-gradient(90deg, #ffe0b2 30%, #fff6e9 100%);
  opacity: 0.5;
  z-index: 0;
  border-radius: 0 0 130rpx 130rpx;
}
</style> 